package com.zjff.show.zjffshow.tool;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

/*
    通过QQ邮箱发送邮件
 */
public class SendEmail {
    /*
        邮件发送接口
     */
    public void sendMail(String descMail, String Title, String Content, File[] files){
        final String fromEmail="1218767583@qq.com";//发件人的邮箱
        final String SmtpCode="brugqgyrbeojjdfi";//SMTP邮箱授权码(密码)
        String ContentType="text/html;charset=utf-8";//请求头
        Properties properties = new Properties();//设置邮箱属性的对象
        properties.setProperty("mail.smtp.host","smtp.qq.com");//设置邮箱服务器的地址
        properties.setProperty("mail.smtp.port","465");//设置邮箱发送端口
        properties.setProperty("mail.smtp.auth","true");//是否加密
        properties.setProperty("mail.debug","true");//是否开启调试
        properties.setProperty("mail.transport.protocol","smtp");//发送形式
        properties.setProperty("mail.smtp.ssl.enable","true");//是否开启HTTPS
        Session session = Session.getInstance(properties, new Authenticator() {//获取加密的请求头
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail,SmtpCode);
            }
        });
        Message message = new MimeMessage(session);
        try {
            message.setFrom( new InternetAddress(fromEmail));//在请求中设置发送人的邮箱
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(descMail));//在请求中设置收件人的邮箱
            message.setSubject(Title);//设置邮件的标题
            //判断是否有附件
            if(files !=null && files.length>0){//表示有附件
                MimeMultipart mimeMultipart = new MimeMultipart();
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(Content,ContentType);
                mimeMultipart.addBodyPart(contentPart);
                for(File file:files){
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataHandler dh = new DataHandler(new FileDataSource(file));
                    attachment.setDataHandler(dh);
                    attachment.setFileName(MimeUtility.encodeText((dh.getName())));//获取文件名
                    mimeMultipart.addBodyPart(attachment);
                }
                mimeMultipart.setSubType("mixed");
                message.setContent(mimeMultipart);
                message.saveChanges();

            }else{//普通邮件
                message.setContent(Content,ContentType);
            }
            Transport transport = session.getTransport();
            transport.connect(fromEmail,SmtpCode);
            Transport.send(message);
        }catch (Exception e){
            e.getMessage();
        }

    }
}
